<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\api\controller;
use think\Db;
use app\common\model\Product as Product_Model;
use app\common\model\ProductStockLog as Stock_Log_Model;
use think\Exception;
use app\common\model\Pandian;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Stock extends Auth
{
    public $noNeedLogin = '';

    public $store = '';

    /**
     * 库存管理--商品分类---添加或者修改商品
     * token
     * name
     * description
     * goods_category_id
     * unit
     * stock
     * is_digit
     * goods_id
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $arr = [
                'name' => $data['name'],
                'description' => $data['description'],
                'product_category_id' => $data['product_category_id'],
                'unit' => $data['unit'],
                'is_digit' => $data['is_digit'],
                'stock' => $data['stock'],
            ];
            if (!key_exists('goods_id', $data)) {
                $info = Product_Model::get(['store_id' => $this->userInfo['store_id'], 'name' => $arr['name']]);
                if ($info) $this->result('商品名称已添加', '', 204);
            }

            if (isset($data['goods_id']) && !empty($data['goods_id'])) {
                Db::name('qt_product')->where('id', $data['product_id'])->update($arr);
                $this->result('操作成功', '', 200);
            } else {
                $arr['store_id'] = $this->userInfo['store_id'];
                $arr['status'] = 1;
                $result = Db::name('qt_product')->insert($arr);
                if($result){
                    $this->result('操作成功', '', 200);
                }
            }


        }
    }

    /**
     * 库存管理--商品管理
     * token
     * keyword
     * product_category_id
     */
    public function lists()
    {
        if ($this->request->isPost()) {

            $data = $this->request->post();

            $sql = DB::name('qt_product')->where(['store_id' => $this->userInfo['store_id'], 'status' => 1]);

            if (!empty($data['keyword'])) {
                $sql = $sql->where('name', 'like', "%{$data['keyword']}%");
            }

            if (!empty($data['product_category_id'])) {
                $sql = $sql->where('product_category_id', $data['product_category_id']);
            }
            $limit = $this->request->post('limit');
            $list = $sql->field('id,name,description,unit,stock,status,product_category_id,is_digit')
                ->where(['status'=>'1'])
                ->paginate($limit)
                ->each(function ($item) {
                    $item['cate_name'] = Db::name('qt_product_category')->where('id', $item['product_category_id'])->value('name');
                    return $item;
                });
            $this->result('获取成功', $list, 200);

        }
    }


    /**
     * 库存管理--商品管理
     * token
     * keyword
     * product_category_id
     */
    public function remove()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $del = Db::name('qt_product')->where('id', $data['id'])->delete();
            if ($del) {
                $this->result('删除成功', '', 200);
            }
            $this->result('删除失败成功', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 库存管理--出入库
     * token
     * keyword
     * product_category_id
     */
    public function output()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['product_id']) || empty($data['stock']) || empty($data['type'])) {
                $this->result('缺少参数', '', 204);
            }
            //type == 1 出库  2 入库
            $goods = Db::name('qt_product')->where('id', $data['product_id'])->find();
            if ($data['type'] == '1') {
                $after = $goods['stock'] - $data['stock'];
            }
            if ($data['type'] == '2') {
                $after = $goods['stock'] + $data['stock'];
            }
            $insert = [
                'product_category_id' => $goods['product_category_id'],
                'store_id' => $this->userInfo['store_id'],
                'before' => $goods['stock'],
                'amount' => $data['stock'],
                'type' => $data['type'],
                'after' => $after,
                'acter' => $this->userInfo['id'],
                'source' => '1',
                'create_time' => time(),
                'product_id'=>$data['product_id'],
            ];
            try {
                Db::startTrans();
                //删除挂账订单
                Db::name('qt_product_stock_log')->insert($insert);
                //更新订单状态
                Db::name('qt_product')->where('id', $data['product_id'])->update(['stock' => $after]);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('出入库失败', '', 204);
            }
            $this->result('出入库成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 库存管理--库存记录
     * token
     * start_time
     * end_time
     * keyword
     */
    public function stockLists()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $sql = Db::name('qt_product_stock_log')->alias('s')
                ->leftJoin('dp_qt_product p', 'p.id=s.product_id')
                ->leftJoin('dp_qt_product_category c', 'c.id=p.product_category_id')
                ->where('s.store_id', $this->userInfo['store_id']);

            if (isset($data['start_time']) && !empty($page['start_time'])) {
                $sql = $sql->whereTime('s.create_time', '>', strtotime($data['start_time']));
            }
            if (isset($data['end_time']) && !empty($page['end_time'])) {
                $sql = $sql->whereTime('s.create_time', '<', strtotime($data['start_time']));
            }
            $page = $this->request->post('page');
            $limit = $this->request->post('limit');
            if (isset($data['keyword']) && !empty($data['keyword'])) {
                $sql = $sql->whereLike('p.name', '%' . $data['keyword'] . '%');
            }
            if (isset($data['start_time']) && !empty($page['start_time']) && isset($data['end_time']) && !empty($data['end_time'])) {
                $sql = $sql->whereBetweenTime('s.create_time', strtotime($data['start_time']), strtotime($data['end_time']));
            }
            $list = $sql->field('s.id,s.before,s.amount,s.after,s.type,s.acter,s.source,p.name goods_name,c.name as cate_name,s.create_time')
                ->paginate($limit)->each(function ($item) {
                    $item['acter_name'] = Db::name('qt_users')->where('id', $item['acter'])->value('real_name');
                    unset($item['acter']);
                    return $item;
                });

            $this->result('获取成功', $list, 200);
        }
    }

    /**
     * 库存管理--提交盘点记录
     * products  json数据[{id:'3',stock:'50',amount:'30',mark:'测试备注'}
     * description盘点备注
     */
    public function pandian()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if (isset($data['goods']) && strlen($data['goods']) > 0) {
                $json_arr = json_decode($data['goods'], true);
                $pandian_id = Db::table('dp_qt_product_pandian')->insertGetId(['store_id' => $this->userInfo['store_id'], 'description' => $data['description'], 'acter' => $this->userInfo['id'], 'create_time' => time()]);
                foreach ($json_arr as $item) {
                    $product = Db::table('dp_qt_product')->where(['store_id' => $this->userInfo['store_id'], 'id' => $item['id']])->find();
                    Db::table('dp_qt_product_pandian_item')->insert([
                        'pandian_id' => $pandian_id,
                        'store_id' => $this->userInfo['store_id'],
                        'mark' => $item['mark'],
                        'product_id' => $item['id'],
                        'origin_stock' => $product['stock'],
                        'amount' => $item['amount'],
                        'loss' => abs($product['stock'] - $item['amount']),
                        'create_time' => time()
                    ]);
                    Db::table('dp_qt_product_stock_log')->insert([
                        'product_id' => $item['id'],
                        'store_id' => $this->userInfo['store_id'],
                        'before' => $product['stock'],
                        'amount' => abs($product['stock'] - $item['amount']),
                        'after' => $item['amount'],
                        'type' => $product['stock'] > $item['amount'] ? '2' : '1',
                        'acter' => $this->userInfo['store_id'],
                        'source' => 3,
                        'create_time' => time()
                    ]);
                    Db::table('dp_qt_product')->where(['store_id' => $this->userInfo['store_id'], 'id' => $item['id']])->setField($item['amount']);
                }
            }
            $this->result('操作成功', '', 200);
        }
    }

    /**
     * 库存管理--获取商品库存列表
     * token
     * product_ids
     */
    public function getStockList()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (key_exists('product_ids', $data) && isset($data['product_ids'])) {
                $sql = Stock_Log_Model::where('status', 1)
                    ->field('id,name,stock');
                if (strpos($data['product_ids'], ',')) {
                    $product_ids = explode(',', $data['product_ids']);
                    $sql = $sql->where('id', 'in', $product_ids);
                } else {
                    $sql = $sql->where('id', $data['product_ids']);
                }
                $list = $sql->select();

                $this->result('获取成功', $list, 200);

            } else {
                $this->result('缺少必要参数', '', 204);
            }
        }
    }

    /**
     * 盘点记录
     */
    public function panLists()
    {
        if ($this->request->isPost()) {
            $list = Pandian::where(['store_id' => $this->userInfo['store_id']])->field('id,description,acter,create_time')->paginate(10)->each(function ($item) {
                return $item['acter_name'] = Db::name('qt_users')->where('id', $item['acter'])->value('real_name');
            });
            $this->result('获取成功', $list, 200);
        } else {
            $this->result('非法请求', '', 204);
        }

    }


    /**
     * 盘点详情
     */
    public function panDetail()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_product_pandian_item')
                ->field('ppi.*,p.name')
                ->alias('ppi')
                ->leftJoin('qt_product p', 'p.id = ppi.product_id')
                ->where('pandian_id', $getData['id'])->select();
            $this->result('获取成功', $data, 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }

}
